<template>
  <div class="home">
    <dv-full-screen-container class="container">
      <div class="header">
        <div class="title">
          <div class="logo">
            <img
              :src="Logo"
              :style="{
                width: `${100 / dpr}px`,
                height: `${100 / dpr}px`
              }"
            />
          </div>
          <h1>智能仓储管理看板</h1>
          <div class="time">{{ time }}</div>
        </div>
      </div>
      <div class="body">
        <div class="left">
          <div class="left-top">
            <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
              <div style="display: flex;flex-direction: column;height: 100%;">
                <div class="basic-title">储位利用率</div>
                <div style="width: 100%;" id="storage-usage"></div>
              </div>
            </dv-border-box-10>
          </div>
          <div class="left-bottom">
            <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
              <div style="display: flex;flex-direction: column;height: 100%;">
                <div class="basic-title">分时出入库</div>
                <div style="display: flex;flex-direction: column;height: 100%;flex: 1;">
                  <div style="flex: 1;">
                    <div id="time-in"></div>
                  </div>
                  <div style="flex: 1;">
                    <div id="time-out"></div>
                  </div>
                </div>
              </div>
            </dv-border-box-10>
          </div>
        </div>
        <div class="center">
          <div class="center-center">
            <div class="four-item">
              <div class="specific-item">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div>总储位数</div>
                  <count-to :start-val="0" :end-val="manageTitle?.allStorageCount" :duration="1500" class="card-panel-num" />
                </dv-border-box-10>
              </div>
              <div class="specific-item">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div>出库母托数</div>
                  <count-to :start-val="0" :end-val="manageTitle?.outPalletCount" :duration="1500" class="card-panel-num" />
                </dv-border-box-10>
              </div>
              <div class="specific-item">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div>UP</div>
                  <count-to :start-val="0" :end-val="manageTitle?.UP" :duration="1500" class="card-panel-num" />
                </dv-border-box-10>
              </div>
              <div class="specific-item">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div>剩余储位数</div>
                  <count-to :start-val="0" :end-val="manageTitle?.availableStorages" :duration="1500" class="card-panel-num" />
                </dv-border-box-10>
              </div>
            </div>
            <div class="four-item">
              <div class="specific-item">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div>储位利用率</div>
                  <count-to :start-val="0" :end-val="manageTitle?.storageUtilization" :decimals=2 suffix="%" :duration="1500" class="card-panel-num" />
                </dv-border-box-10>
              </div>
              <div class="specific-item">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div>入库母托数</div>
                  <count-to :start-val="0" :end-val="manageTitle?.inPalletCount" :duration="1500" class="card-panel-num" />
                </dv-border-box-10>
              </div>
              <div class="specific-item">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div>FIFO</div>
                  <count-to :start-val="0" :end-val="fifoInfo?.FIFO" :duration="1500" class="card-panel-num" />
                </dv-border-box-10>
              </div>
              <div class="specific-item">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div>库存料号数</div>
                  <count-to :start-val="0" :end-val="manageTitle?.skuCount" :duration="1500" class="card-panel-num" />
                </dv-border-box-10>
              </div>
            </div>
            <div class="two-item">
              <div class="center-left-table">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div class="content-title">库存管理</div>
                  <div class="text-container">
                    <div class="each-item">
                      <div class="white-item">低于下限料号数</div>
                      <div class="red-item">{{ inventoryManage?.lowSkuCount ? inventoryManage?.lowSkuCount : 0 }}</div>
                    </div>
                    <div class="each-item">
                      <div class="white-item">高于上限料号数</div>
                      <div class="red-item">{{ inventoryManage?.excessSkuCount ? inventoryManage?.excessSkuCount : 0 }}</div>
                    </div>
                  </div>
                  <el-table empty-text="暂无数据" :data="inventoryList" :row-class-name="tableRowClassName" :max-height="inventoryMaxHeight">
                    <el-table-column prop="productNo" label="料号" :width="120 / dpr"/>
                    <el-table-column prop="qty" label="数量" :width="75/ dpr"/>
                    <el-table-column prop="stockLimits" label="上下限" />
                    <el-table-column prop="diffQty" label="差异数量" />
                    <el-table-column prop="diffRate" label="差异比例" />
                  </el-table>
                </dv-border-box-10>
              </div>
              <div class="center-right-table">
                <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                  <div class="content-title">库龄管理</div>
                  <div class="text-container">
                    <div class="each-item">
                      <div class="white-item">超期料号数</div>
                      <div class="green-item">{{ inventoryAgingManage?.expiredLotCount ? inventoryAgingManage?.expiredLotCount : 0 }}</div>
                    </div>
                    <div class="each-item">
                      <div class="white-item">超期批次数</div>
                      <div class="green-item">{{ inventoryAgingManage?.expiredSkuCount ? inventoryAgingManage?.expiredSkuCount : 0 }}</div>
                    </div>
                  </div>
                  <el-table empty-text="暂无数据" :data="ageList" :row-class-name="tableRowClassName" :max-height="ageMaxHeight">
                    <el-table-column prop="productNo" label="料号" :width="120 / dpr"/>
                    <el-table-column prop="batchCode" label="批号" :width="75 / dpr"/>
                    <el-table-column prop="qty" label="库存数量" :width="105 / dpr"/>
                    <el-table-column prop="expiredDays" label="超期天数" />
                    <el-table-column prop="targetAging" label="目标库龄" />
                  </el-table>
                </dv-border-box-10>
              </div>
            </div>
          </div>
          <div class="center-bottom">
            <div class="device-table">
              <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                <div class="content-title">设备状态</div>
                <el-table empty-text="暂无数据" :data="deviceList" :row-class-name="tableRowClassName" :max-height="deviceMaxHeight">
                  <el-table-column prop="deviceName" label="设备名称" :width="105 / dpr">
                    <template slot-scope="scope">
                      {{ (scope.row.deviceName || '').split('-')[1] || '' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="deviceCode" label="设备编号" :width="180 / dpr"/>
                  <el-table-column prop="status" label="状态" :width="75 / dpr">
                    <template slot-scope="scope">
                      <div
                        :style="{
                          textAlign: 'center',
                          background: `radial-gradient(circle, ${getColor(scope.row.status)} 50%, transparent 90%)`,
                          width: `${30 / dpr}px`,
                          height: `${30 / dpr}px`,
                          borderRadius: '50%',
                          boxShadow: `0 0 5px ${getColor(scope.row.status)}, 0px 0 5px ${getColor(scope.row.status)}, inset 0 0 20px rgba(255, 255, 255, 0.5)`
                        }"
                      ></div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="startTime" label="启动时间">
                    <template slot-scope="scope">
                      {{ formatTime(scope.row.startTime) }}
                    </template>
                  </el-table-column>
                </el-table>
              </dv-border-box-10>
            </div>
            <div class="device-chart">
              <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
                <div class="content-title">设备OEE</div>
                <div style="width: 100%;" id="device-oee"></div>
              </dv-border-box-10>
            </div>
          </div>
        </div>
        <div class="right">
          <div class="right-top-table">
            <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
              <div class="content-title">隔离库存</div>
              <div class="text-container">
                <div class="each-item">
                  <div class="white-item">隔离料号数</div>
                  <div style="color: #F56C6C;font-size: 1.5rem;font-weight: 600;">{{ frozenManage?.frozenSkuCount ? frozenManage?.frozenSkuCount : 0 }}</div>
                </div>
                <div class="each-item">
                  <div class="white-item">隔离批次数</div>
                  <div style="color: #F56C6C;font-size: 1.5rem;font-weight: 600;">{{ frozenManage?.frozenLotCount ? frozenManage?.frozenLotCount : 0 }}</div>
                </div>
              </div>
              <el-table empty-text="暂无数据" :data="isolatedList" :row-class-name="tableRowClassName" :max-height="isolatedMaxHeight">
                <el-table-column prop="productNo" label="料号"  :width="140 / dpr"/>
                <el-table-column prop="qty" label="数量" :width="90 / dpr"/>
                <el-table-column prop="frozenReason" label="隔离原因" />
              </el-table>
            </dv-border-box-10>
          </div>
          <div class="right-bottom-table">
            <dv-border-box-10 class="content-border" :color="['rgb(35 135 188)', 'rgb(0, 187, 236)']">
              <div style="display: flex;flex-direction: column;height: 100%;">
                <div class="content-title">先进先出</div>
                <div style="display: flex;flex-direction: column;height: 100%;flex: 1;">
                  <div id="fifo-chart"></div>
                  <div class="fifo-table">
                    <el-table empty-text="暂无数据" :data="frozenList" :row-class-name="tableRowClassName" :max-height="frozenMaxHeight">
                      <el-table-column prop="productNo" label="料号" />
                      <el-table-column prop="batchCode" label="批号" />
                      <el-table-column prop="qty" label="数量" />
                    </el-table>
                  </div>
                </div>
              </div>
            </dv-border-box-10>
          </div>
        </div>
      </div>
    </dv-full-screen-container>
  </div>
</template>

<script>
import Logo from '../assets/img/IWS_LOGO_N.png'
import * as echarts from 'echarts'
import CountTo from 'vue-count-to'
import { EventSourcePolyfill } from 'event-source-polyfill'
export default {
  name: 'Home',
  components: {
    CountTo,
  },
  data() {
    return {
      time: '',
      timer: [],
      es: null,
      // 图表
      storageUsageChart: null,
      inChart: null,
      outChart: null,
      deviceChart: null,
      fifoChart: null,
      inChartData: [],
      outChartData: [],
      timeList: [],
      deviceData: [],
      deviceDate: [],
      // 列表
      inventoryList: [],
      ageList: [],
      deviceList: [],
      isolatedList: [],
      frozenList: [],
      // 列表高度
      inventoryMaxHeight: 0,
      ageMaxHeight: 0,
      isolatedMaxHeight: 0,
      frozenMaxHeight: 0,
      deviceMaxHeight: 0,
      // 标题相关
      manageTitle: null,
      // 库存管理
      inventoryManage: null,
      // 库龄管理
      inventoryAgingManage: null,
      // 冻结管理
      frozenManage: null,
      // 先进先出
      fifoInfo: null,
      deviceManage: null,
      Logo: Logo,
      dpr: null
    }
  },
  mounted() {
    // console.log('当前的像素比:' + window.devicePixelRatio)
    this.dpr = window.devicePixelRatio
    console.log(process.env.VUE_APP_BASE_API)
    this.getTime()
    this.timer = setInterval(() => {
      this.getTime()
    }, 1000)
    if (this.dpr) {
      this.getHead()
      this.initAutoScroll()
      this.createSSE()
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    createSSE() {
      const baseURL = process.env.VUE_APP_BASE_API
      this.es = new EventSourcePolyfill(`${baseURL}api/sse/manageDashboard`)
      this.es.onopen = () => {
        console.log('连接成功')
      }
      this.es.onclose = () => {
        console.log('连接断开')
      }
      this.es.onmessage = (e) => {
        const parsedData = JSON.parse(e.data)
        console.log(parsedData)
        // 标题相关
        this.manageTitle = parsedData.data.storageManage.manageTitleVo || {}
        // 库存管理相关
        this.inventoryManage = parsedData.data.storageManage.inventoryManageVo || {}
        this.inventoryList = parsedData.data.storageManage.inventoryManageVo.inventoryManageDataList || []
        // 库龄管理相关
        this.inventoryAgingManage = parsedData.data.storageManage.inventoryAgingManageVo || {}
        this.ageList = parsedData.data.storageManage.inventoryAgingManageVo.inventoryAgingManageDataList || []
        // 隔离库存相关
        this.frozenManage = parsedData.data.storageManage.frozenManageVo || {}
        // this.isolatedList = parsedData.data.storageManage.frozenManageVo.frozenMaterials || []
        this.isolatedList = [
          ...parsedData.data.storageManage.frozenManageVo.frozenMaterials,
          ...parsedData.data.storageManage.frozenManageVo.frozenMaterials,
          ...parsedData.data.storageManage.frozenManageVo.frozenMaterials,
          ...parsedData.data.storageManage.frozenManageVo.frozenMaterials,
          ...parsedData.data.storageManage.frozenManageVo.frozenMaterials
        ]
        // 设备相关
        this.deviceList = parsedData.data.storageManage?.deviceManageVo?.deviceStatusManageDataList || []
        // FIFO
        this.frozenList = parsedData.data.storageManage.fifoVo?.errorMaterialInfos || []
        // 图表数据
        this.inChartData = parsedData.data.storageManage.hourlyIoManageVo.inQtyList || {}
        this.timeList = parsedData.data.storageManage.hourlyIoManageVo.timeList || []
        this.outChartData = parsedData.data.storageManage.hourlyIoManageVo.outQtyList || {}
        this.fifoInfo = parsedData.data.storageManage.fifoVo || {}
        // console.log(parsedData.data.storageManage.deviceManageVo)
        this.deviceData = parsedData.data.storageManage?.deviceManageVo?.deviceNameList ? parsedData.data.storageManage.deviceManageVo.deviceNameList.map(item => {
          return item.split('-')[1]
        }) : []
        this.deviceDate = parsedData.data.storageManage?.deviceManageVo?.deviceOeeList || []
        this.initChart()
        this.getHeight()
      }
      this.es.onerror = (err) => {
        this.handleError() 
        console.log(err)
      }
    },
    getHead() {
      setTimeout(() => {
        this.$nextTick(() => {
          const head = document.getElementsByClassName('el-table__header-wrapper')
          this.inventoryMaxHeight = head[0].offsetHeight * 3
          this.ageMaxHeight = head[1].offsetHeight * 3
          this.deviceMaxHeight = head[2].offsetHeight * 3
          this.isolatedMaxHeight = head[3].offsetHeight * 3
          this.frozenMaxHeight = head[4].offsetHeight * 3
        })
      }, 100)
    },
    getHeight() {
      this.$nextTick(() => {
        const head = document.getElementsByClassName('el-table__header-wrapper')
        if (this.inventoryList.length === 0) {
          this.inventoryMaxHeight = head[0].offsetHeight * 3
        }
        if (this.ageList.length === 0) {
          this.ageMaxHeight = head[1].offsetHeight * 3
        }
        if (this.deviceList.length === 0) {
          this.deviceMaxHeight = head[2].offsetHeight * 3
        }
        if (this.isolatedList.length === 0) {
          this.isolatedMaxHeight = head[3].offsetHeight * 3
        }
        if (this.frozenList.length === 0) {
          this.frozenMaxHeight = head[4].offsetHeight * 3
        }
        // 步数
        const box = document.getElementsByClassName('el-table__body-wrapper')
        const boxStep = document.getElementsByClassName('el-table__body')
        const targetScrollOne = (box[0].scrollTop + boxStep[0]?.children[1]?.children[0]?.offsetHeight) || 0
        const targetScrollTwo = (box[1].scrollTop + boxStep[1]?.children[1]?.children[0]?.offsetHeight) || 0
        const targetScrollThree = (box[2].scrollTop + boxStep[2]?.children[1]?.children[0]?.offsetHeight) || 0
        const targetScrollFour = (box[3].scrollTop + boxStep[3]?.children[1]?.children[0]?.offsetHeight) || 0
        const targetScrollFive = (box[4].scrollTop + boxStep[4]?.children[1]?.children[0]?.offsetHeight) || 0
        // 容器大小
        const oneTable = document.getElementsByClassName('center-left-table')[0].offsetHeight
        const twoTable = document.getElementsByClassName('center-right-table')[0].offsetHeight
        const threeTable = document.getElementsByClassName('device-table')[0].offsetHeight
        const fourTable = document.getElementsByClassName('right-top-table')[0].offsetHeight
        const fiveTable = document.getElementsByClassName('fifo-table')[0].offsetHeight
        // 标题(随便用一个:需要减去)
        const eachTitle = document.getElementsByClassName('content-title')[0].offsetHeight
        // 俩边文字(随便用一个:需要减去)
        const textContainer = document.getElementsByClassName('text-container')[0].offsetHeight
        if (oneTable && this.inventoryMaxHeight === head[0].offsetHeight * 3) {
          const adjustedHeight = oneTable - eachTitle - textContainer
          this.inventoryMaxHeight = Math.floor(adjustedHeight / targetScrollOne) * targetScrollOne
        }
        if (twoTable && this.ageMaxHeight === head[1].offsetHeight * 3) {
          const adjustedHeight = twoTable - eachTitle - textContainer
          this.ageMaxHeight = Math.floor(adjustedHeight / targetScrollTwo) * targetScrollTwo
        }
        if (threeTable && this.deviceMaxHeight === head[2].offsetHeight * 3) {
          const adjustedHeight = threeTable - eachTitle
          this.deviceMaxHeight = Math.floor(adjustedHeight / targetScrollThree) * targetScrollThree
        }
        if (fourTable && this.isolatedMaxHeight === head[3].offsetHeight * 3) {
          const adjustedHeight = fourTable - eachTitle - textContainer
          this.isolatedMaxHeight = Math.floor(adjustedHeight / targetScrollFour) * targetScrollFour
        }
        if (fiveTable && this.frozenMaxHeight === head[4].offsetHeight * 3) {
          const adjustedHeight = fiveTable
          this.frozenMaxHeight = Math.floor(adjustedHeight / targetScrollFive) * targetScrollFive
        }
      })
    },
    initAutoScroll() {
      this.$nextTick(() => {
        const t = 3000 // 滚动间隔时间
        const box = document.getElementsByClassName('el-table__body-wrapper')
        const content = document.getElementsByClassName('el-table__body')
        // 定义一个平滑滚动的函数
        const smoothScroll = (element, target) => {
          const start = element.scrollTop
          const change = target - start
          const duration = 1500 // 滚动动画持续时间
          let startTimestamp = null
          const step = (timestamp) => {
            if (!startTimestamp) startTimestamp = timestamp
            const time = timestamp - startTimestamp
            const current = easeInOutCubic(time, start, change, duration)
            element.scrollTop = current
            if (time < duration) {
              requestAnimationFrame(step)
            }
          }
          requestAnimationFrame(step)
        }
        // 缓动函数，用于平滑滚动
        const easeInOutCubic = (t, b, c, d) => {
          t /= d / 2
          if (t < 1) return c / 2 * t * t * t + b
          t -= 2;
          return c / 2 * (t * t * t + 2) + b
        }
        this.timer = setInterval(() => {
          for (let i = 0; i < box.length; i++) {
            // const rows = content[i].querySelectorAll('.el-table__row') // 获取所有行
            // const currentRow = rows[Math.floor(box[i].scrollTop / box[i].offsetHeight)] // 当前行
            // if (currentRow) {
            //   const targetScrollTop = box[i].scrollTop + currentRow.offsetHeight // 当前行的高度
            //   if (targetScrollTop >= content[i].scrollHeight - box[i].offsetHeight) {
            //     smoothScroll(box[i], 0) // 如果到达底部，滚动到顶部
            //   } else {
            //     smoothScroll(box[i], targetScrollTop) // 滚动到当前行的高度
            //   }
            // } else {
            //   smoothScroll(box[i], 0) // 如果没有当前行，滚动到顶部
            // }
            const wrapper = box[i]
            const contentEl = content[i]
            const rows = Array.from(contentEl.querySelectorAll('.el-table__row'))
            const scrollTop = wrapper.scrollTop
            const wrapperHeight = wrapper.offsetHeight
            const contentHeight = contentEl.scrollHeight
            let currentIndex = 0
            for (let j = 0; j < rows.length; j++) {
              if (rows[j].offsetTop <= scrollTop) {
                currentIndex = j
              } else {
                break
              }
            }
            const nextIndex = currentIndex + 1
            let targetScrollTop
            if (nextIndex >= rows.length || scrollTop + wrapperHeight >= contentHeight - 1) {
              targetScrollTop = 0
            } else {
              targetScrollTop = rows[nextIndex].offsetTop
            }
            smoothScroll(wrapper, targetScrollTop)
          }
        }, t)
      })
    },
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    getColor(val) {
      switch (val) {
        case 1:
          return '#67C23A';
        case 0:
          return '#ff0000';
        default:
          return '#fff';
      }
    },
    initChart() {
      // 入库图表
      const timeInDom = document.getElementById('time-in')
      if (!this.inChart) {
        this.inChart = echarts.init(timeInDom)
      }
      let option
      option = {
        grid: {
          top: 40,
          bottom: 30,
          left: 30,
          right: 20
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          orient: 'horizontal',
          top: 10,
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: this.timeList,
          axisLabel: {
            fontSize: 8,
            color: '#fff',
            fontWeight: 'bold'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            fontSize: 14,
            color: '#fff',
            fontWeight: 'bold'
          }
        },
        series: [
          {
            data: this.inChartData,
            name: '入库',
            type: 'bar',
            barWidth: 15,
            barCategoryGap: '40%',
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: '#B0E0E6'
                  },
                  {
                    offset: 1,
                    color: '#56A5EC'
                  }
                ],
                global: false
              }
            },
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      }
      this.inChart.setOption(option)
      // 出库图标
      const timeOutDom = document.getElementById('time-out')
      if (!this.outChart) {
        this.outChart = echarts.init(timeOutDom)
      }
      let option2
      option2 = {
        grid: {
          top: 40,
          bottom: 30,
          left: 30,
          right: 20
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          orient: 'horizontal',
          top: 10,
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: this.timeList,
          axisLabel: {
            fontSize: 8,
            color: '#fff',
            fontWeight: 'bold'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            fontSize: 14,
            color: '#fff',
            fontWeight: 'bold'
          }
        },
        series: [
          {
            data: this.outChartData,
            name: '出库',
            type: 'bar',
            barWidth: 20,
            barCategoryGap: '40%',
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 1,
                x2: 0,
                y2: 0,
                colorStops: [
                  {
                    offset: 0,
                    color: '#FF8C00' // 起始颜色（深橙色）
                  },
                  {
                    offset: 1,
                    color: '#FFA500' // 结束颜色（浅橙色）
                  }
                ]
              }
            },
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      }
      this.outChart.setOption(option2)
      // 设备图标
      const deviceDom = document.getElementById('device-oee')
      if (!this.deviceChart) {
        this.deviceChart = echarts.init(deviceDom)
      }
      let option4
      option4 = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          orient: 'horizontal',
          top: 10,
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: this.deviceData,
          axisLabel: {
            fontSize: 12,
            color: '#fff',
            fontWeight: 'bold'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            fontSize: 14,
            color: '#fff',
            fontWeight: 'bold'
          }
        },
        series: [
          {
            data: this.deviceDate,
            name: '运行',
            type: 'bar',
            barWidth: 40,
            barCategoryGap: '40%',
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: '#B7EB8F' // 浅一点的绿色（#67C23A的亮色变体）
                  },
                  {
                    offset: 1,
                    color: '#67C23A' // 主色
                  }
                ],
                global: false
              }
            },
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          }
        ]
      }
      this.deviceChart.setOption(option4)
      // 储位利用率
      const storageUsageDom = document.getElementById('storage-usage')
      if (!this.storageUsageChart) {
        this.storageUsageChart = echarts.init(storageUsageDom)
      }
      let option3
      option3 = {
        series: [
          {
            type: 'gauge',
            axisLine: {
              lineStyle: {
                width: 15,
                color: [
                  [0.7, {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 1,
                    y2: 0,
                    colorStops: [
                      { offset: 0, color: '#34c759' },
                      { offset: 1, color: '#f7a801' }
                    ],
                    global: false
                  }],
                  [0.9, {
                    type: 'linear',
                    x: 0,
                    y: 0,
                    x2: 1,
                    y2: 0,
                    colorStops: [
                      { offset: 0, color: '#f7a801' },
                      { offset: 1, color: '#e53935' }
                    ],
                    global: false
                  }],
                  [1, '#e53935']
                ]
              }
            },
            pointer: {
              itemStyle: {
                color: 'auto'
              },
              width: 5
            },
            axisTick: {
              distance: -15,
              length: 10,
              lineStyle: {
                color: '#fff',
                width: 1
              }
            },
            splitLine: {
              distance: -15,
              length: 15,
              lineStyle: {
                color: '#fff',
                width: 1
              }
            },
            axisLabel: {
              color: '#fff',
              distance: 20,
              fontSize: 14
            },
            detail: {
              valueAnimation: true,
              formatter: '{value} %',
              color: '#fff',
              fontSize: 16 // 减小字体大小
            },
            data: [
              {
                // TODO: x轴坐标需要根据实际情况调整, 先写死
                value: this.manageTitle.storageUtilization.toFixed(2) || 0
              }
            ]
          }
        ]
      }
      this.storageUsageChart.setOption(option3)
      const fifoDom = document.getElementById('fifo-chart')
      if (!this.fifoChart) {
        this.fifoChart = echarts.init(fifoDom)
      }
      let option5
      option5 = {
        grid: {
          top: 40,
          bottom: 30,
          left: 30,
          right: 40
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          orient: 'horizontal',
          top: 10,
          textStyle: {
            color: '#fff'
          },
        },
        xAxis: {
          type: 'category',
          data: this.fifoInfo.date,
          axisLabel: {
            fontSize: 8,
            color: '#fff',
            fontWeight: 'bold',
            formatter: function(value) {
              const index = value.indexOf('-')
              return index !== -1 ? value.slice(index + 1) : value
            }
          }
        },
        yAxis: [
          // 原有y轴配置
          {
            type: 'value',
            axisLabel: {
              fontSize: 12,
              color: '#fff',
              fontWeight: 'bold'
            }
          },
          // 新增的y轴配置
          {
            type: 'value',
            name: '占比',
            min: 0,
            max: 100,
            axisLabel: {
              fontSize: 12,
              color: '#fff',
              fontWeight: 'bold',
              formatter: '{value} %'
            },
          }
        ],
        series: [
          // 原有bar系列配置
          {
            data: [0, 0, 0, 0, 0, 0, 0],
            type: 'bar',
            barWidth: 20,
            barCategoryGap: '40%',
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: '#B0E0E6'
                  },
                  {
                    offset: 1,
                    color: '#56A5EC'
                  }
                ],
                global: false
              }
            },
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)'
            }
          },
          // 新增的line系列配置
          {
            name: '占比',
            type: 'line',
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + '%';
              }
            },
            data: [100, 100, 100, 100, 100, 100, 100]
          }
        ]
      }
      this.fifoChart.setOption(option5)
    },
    handleError() {
      if (this.es.readyState === EventSourcePolyfill.CLOSED) {
        this.es.close()
        this.createSSE()
      } else if (this.es.readyState === EventSourcePolyfill.CONNECTING) {
        console.log('正在重连中')
      }
    },
    tableRowClassName({ rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'warning-row'
      } else {
        return 'success-row'
      }
    },
    getTime() {
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let hh =
        new Date().getHours() < 10
          ? '0' + new Date().getHours()
          : new Date().getHours()
      let mf =
        new Date().getMinutes() < 10
          ? '0' + new Date().getMinutes()
          : new Date().getMinutes()
      let ss =
        new Date().getSeconds() < 10
          ? '0' + new Date().getSeconds()
          : new Date().getSeconds()
      this.time = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
    }
  },
}
</script>

<style lang="less" scoped>
.container {
  // background: rgb(0, 116, 194);
  background-image: url('../assets/img/1-背景.png');
  background-size: 100% 100%;
  height: 100%;
}
.red {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #ff0000;
  margin-left: 45px;
}
.green {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #06eb00;
  margin-left: 45px;
}
.yellow {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #ffee00;
  margin-left: 45px;
}
.header {
  text-align: center;
  background-image: url('../assets/img/2-标题23.png');
  background-size: 100% 110%;
  height: 5%;
  h1 {
    margin: 0;
    color: #fff;
    font-size: 40px;
  }
  .title {
    position: relative;
  }
  .logo {
    color: #fff;
    position: absolute;
    left: 1%;
    top: -20px;
  }
  .time {
    position: absolute;
    right: 2%;
    color: #fff;
    top: 0.5%;
    font-size: 24px;
    font-weight: bold;
  }
}
.body {
  width: 99%;
  height: 94%;
  display: flex;
  box-sizing: border-box;
  gap: 5px;
  margin: 5px auto;
  .content-title {
    box-sizing: border-box;
    color: #fff;
    text-align: center;
    font-size: 1.8rem;
    font-weight: 600;
  }
  .basic-title {
    padding: 10px;
    box-sizing: border-box;
    color: #fff;
    text-align: center;
    font-size: 1.5rem;
    font-weight: 600;
  }
  .text-container {
    display: flex;
    justify-content: space-between;
    margin: 5px 0;
    .each-item {
      flex: 1;
      text-align: center;
      .white-item {
        color: #fff;
        font-size: 1.5rem;
        font-weight: 600;
      }
      .red-item {
        color: #F56C6C;
        font-size: 1.5rem;
        font-weight: 600;
      }
      .green-item {
        color: #67C23A;
        font-size: 1.5rem;
        font-weight: 600;
      }
    }
  }
  .left {
    // flex: 2;
    width: 20%;
    display: flex;
    flex-direction: column;
    gap: 5px;
    .left-top {
      flex: 2;
      #storage-usage {
        height: 100%;
      }
    }
    .left-bottom {
      flex: 3;
      #time-in {
        width: 100%;
        height: 100%;
      }
      #time-out {
        width: 100%;
        height: 100%;
      }
    }
  }
  .center {
    // flex: 6;
    width: 60%;
    display: flex;
    flex-direction: column;
    gap: 5px;
    .center-center {
      flex: 6;
      display: flex;
      flex-direction: column;
      gap: 5px;
      .four-item {
        flex: 1;
        display: flex;
        gap: 5px;
        .specific-item {
          flex: 1;
          color: #fff;
          text-align: center;
          font-size: 20px;
          line-height: 40px;
          font-weight: bold;
          .card-panel-num {
            color: #3de7c9;
            font-size: 30px;
            display: block;
          }
        }
        .center-left-table {
          flex: 1;
          height: 100%;
        }
        .center-right-table {
          flex: 1;
          height: 100%;
        }
      }
      .two-item {
        display: flex;
        gap: 5px;
        flex: 4;
        // width: 100%;
        .center-left-table {
          // flex: 1;
          width: 50%;
        }
        .center-right-table {
          // flex: 1;
          width: 50%;
        }
      }
    }
    // .center-center {
    //   flex: 4;
    //   display: flex;
    //   gap: 5px;
    // }
    .center-bottom {
      flex: 4;
      display: flex;
      gap: 5px;
      .device-table {
        flex: 1;
        height: 100%;
      }
      .device-chart {
        flex: 1;
        height: 100%;
        #device-oee {
          height: 100%;
        }
      }
    }
  }
  .right {
    // flex: 2;
    width: 20%;
    display: flex;
    flex-direction: column;
    gap: 5px;
    .right-top-table{
      flex: 2;
      height: 100%;
    }
    .right-bottom-table{
      flex: 3;
      height: 100%;
      #fifo-chart {
        flex: 1;
      }
      .fifo-table {
        flex: 1;
      }
    }
  }
}

// ------------------------------el-table---------------------
// el-table的margin
/deep/ .el-table {
  margin: 0 !important;
}
// el-tablk的宽度占满
/deep/ .el-table__body {
  width: 100% !important;
}

/deep/ tr td .cell {
  font-size: larger !important;
}

// /deep/ .el-table__header th .cell {
//   color: #fff !important;
//   background-color: #000 !important;
// }

/deep/ .el-table__header-wrapper {
  .el-table__header {
    width: 100% !important;
    [name="gutter"] {
      display: none !important;
    }
  }
  th.el-table__cell.gutter {
    display: none !important;
  }
}

/deep/ .el-table__header tr .el-table__cell {
  background: linear-gradient(to bottom, #054ea2, #023575, #002a5e);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.el-table__body tr:hover > td {
  background-color: #1f68ddc0 !important;
}

.el-table th.el-table__cell {
  /* color: #05c3ff; */
  background-color: rgba(8, 119, 223, 0.6);
}

/deep/ .el-table th.el-table__cell > .cell {
  font-size: 18px !important;
}

.el-table--border {
  border: none;
}

.el-table,
.el-table__expanded-cell {
  background-color: transparent;
}

/deep/ .el-table__body-wrapper {
  background-color: rgba(19, 95, 236, 0.2) !important;
}

.el-table th,
.el-table tr,
.el-table td {
  background-color: transparent;
  color: #fff ;
  border-color: transparent !important;
}

/deep/.el-table .warning-row {
  background: rgba(38, 66, 105, 0.5) !important;
}

/deep/.cell {
  text-align: center;
}

/deep/.el-table .success-row {
  //这里可以修改颜色
  background-image: linear-gradient(
    to left,
    rgba(3, 58, 141, 0.685) 0%,
    rgba(15, 30, 56, 0.8) 65%,
    rgba(22, 58, 109, 0.699) 100%
  );
}

.el-table::before {
  display: none !important;
}

.content-border ::-webkit-scrollbar {
  width: 0px; /* 设置滚动条的宽度 */
}
</style>
